﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Popup;
using DevExpress.XtraGrid.Editors;
using DevExpress.XtraLayout;
using DevExpress.Utils.Win;
using mendian;
using DiaoPaiDaYin;
using DevExpress.XtraGrid.Demos.util;
using DXApplicationTangche.UC.门店下单.DTO;
using DXApplicationTangche.service;
using DXApplicationTangche.UC.坚山;
//using DXApplicationTangche.model;
using DXApplicationTangche.原型;
using DXApplicationTangche.Utils;
using System.Diagnostics;
using DXApplicationTangche.DTO.尖山;
using System.IO;
using DXApplicationTangche.UC.销售记录.service;
using DXApplicationTangche.DTO;
using DXApplicationTangche.UC.款式异常;
using DXApplicationTangche.UC.门店下单;
using DXApplicationTangche.UC.客户管理;
using DXApplicationTangche.UC.客户CRM.Service;

namespace DXApplicationTangche.UC.坚山上海.坚山上海新
{
    public partial class Form坚山上海订单创建 : DevExpress.XtraEditors.XtraForm
    {
        /// <summary>
        /// 订单充血类
        /// </summary>
        private OrderModel orderModel = new OrderModel();
        private int trueAddressId;//真客户地址id
        private Boolean expressToStore = false;
        private List<CustomerInformation> customerInformations = new List<CustomerInformation>();// 量体
        private 客户CRM.Service.CustomerOrderCommitDTO addressDTO = new 客户CRM.Service.CustomerOrderCommitDTO();
        public Form坚山上海订单创建()
        {
            InitializeComponent();
            Frm客户.cUSTOMER_ID = 0;
            Frm客户.customer_name = "";
            Frm客户.customer_countid = 0;
            Frm客户.aDDRESS_ID = 0;
            this.trueAddressId = Frm客户.aDDRESS_ID;
            //this.initData();    //  测试方法
            this.gridControl订单分录一览.DataSource = this.orderModel.OrderDtos;
            //this.textEdit订单号.Text = FunctionHelper.generateBillNo_坚山("o_order_p", "ORDER_NO", "KA.DL27.", "000000");
            this.comboBox门店.SelectedIndex = 0;
            this.comboBox店铺.SelectedIndex = 0;
            this.comboBox邮寄地址.SelectedIndex = 0;
        }

        public void buildKashiyamaOrderModel(Dto定制下单 dto定制下单, List<尺寸呈现dto> 尺寸呈现dtos)
        {
            this.orderModel.buildKashiyamaAddOrderDtos(dto定制下单, 尺寸呈现dtos);
        }
        private void Frm门店统一下单_Load(object sender, EventArgs e)
        {
            this.查询客户();
        }

        private void 查询客户()
        {
            this.searchLookUpEdit1.Properties.DataSource = CRM客户Service.getCustomerInfoByShopId("52");
        }
        private void 查询客户量体(int customerId)
        {
            this.customerInformations.Clear();
            List<CustomerFItDTO> customerFItDTOs = CRM客户Service.getCustomerFitInfoById(customerId);
            foreach (CustomerFItDTO item in customerFItDTOs)
            {
                if (!String.IsNullOrEmpty(item.itemNameCn))
                {
                    this.customerInformations.Add(new CustomerInformation(item.propertyNameCn, item.itemNameCn));
                }
                else
                {
                    this.customerInformations.Add(new CustomerInformation(item.propertyNameCn, item.fitValue));
                }
            }
            this.gridControl2.DataSource = this.customerInformations;
            this.gridView2.RefreshData();
        }
        #region 选择客户
        private void searchLookUpEdit1_Popup(object sender, EventArgs e)
        {
            //得到当前SearchLookUpEdit弹出窗体
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clearBtn_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }

        private void searchLookUpEdit1View_Click(object sender, EventArgs e)
        {
            var a = this.searchLookUpEdit1.Properties.View.GetSelectedRows();
            foreach (int rowHandle in a)
            {
                Frm客户.cUSTOMER_ID //  no
                    = Convert.ToInt32(this.searchLookUpEdit1.Properties.View.GetRowCellValue(rowHandle, "customerId").ToString());
                Frm客户.customer_name //  no
                    = this.searchLookUpEdit1.Properties.View.GetRowCellValue(rowHandle, "name").ToString();
                //  量体id、地址id
                Frm客户.customer_countid //  no
                    = Convert.ToInt32(this.searchLookUpEdit1.Properties.View.GetRowCellValue(rowHandle, "fitId").ToString());
                Frm客户.aDDRESS_ID //  no
                    = Convert.ToInt32(this.searchLookUpEdit1.Properties.View.GetRowCellValue(rowHandle, "addressId").ToString());
                this.trueAddressId = Frm客户.aDDRESS_ID;
            }
            this.查询客户量体(Frm客户.cUSTOMER_ID);
            this.orderModel = new OrderModel();
            this.锁定地址();
            this.refreshGridControl();
        }

        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearBtn_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit1.ToolTip = null;
            searchLookUpEdit1.EditValue = null;
        }
        private void searchLookUpEdit1_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
                e.DisplayText = Frm客户.customer_name;
        }
        #endregion
        private void tileBarItem1_ItemClick(object sender, TileItemEventArgs e)
        {
            new Form坚山上海款式创建(this).ShowDialog();
        }

        public void refreshGridControl()
        {
            this.gridControl订单分录一览.DataSource = this.orderModel.OrderDtos;
            this.tileView1.RefreshData();
        }

        private void siveorder_Click(object sender, EventArgs e)
        {
            this.splashScreenManager.ShowWaitForm();
            this.splashScreenManager.SetWaitFormCaption("请稍后,正在加载中....");     // 标题
            this.splashScreenManager.SetWaitFormDescription("正在初始化.....");     // 信息
            if (String.IsNullOrWhiteSpace(this.comboBox门店.Text.Trim()))
            {
                MessageBox.Show("请选择下单店铺");
                this.splashScreenManager.CloseWaitForm();
                return;
            }
            if (String.IsNullOrEmpty(this.comboBox店铺.Text))
            {
                MessageBox.Show("请选择店铺");
                this.splashScreenManager.CloseWaitForm();
                return;
            }
            if (Frm客户.cUSTOMER_ID == 0)
            {
                MessageBox.Show("客户为空,请选择客户");
                this.splashScreenManager.CloseWaitForm();
                return;
            }
            foreach (OrderDto orderDto in this.orderModel.OrderDtos)
            {
                orderDto.kashiyamaStoreName = this.comboBox门店.Text.Trim();
                //下单店铺名称
            }
            try
            {
                if (comboBox店铺.Text.Equals("日本"))
                {
                    this.orderModel.buildCustomer(this.addressDTO);
                    //新保存接口
                    DTO销售记录 DTO销售记录 = new DTO销售记录().buildForKashiyama(orderModel.OrderDtos,this.expressToStore);
                    String jsonDTO销售记录 = FunctionHelper.JsonSerialization(DTO销售记录);
                    RestCall.PostHttp(URL.接口url + "/barcode/saveOrder_KASHIYAMA_SHH?StoreName=" + this.comboBox门店.Text.Trim(), jsonDTO销售记录);
                }
                else if (comboBox店铺.Text.Equals("美国"))
                {
                    //this.orderModel.SaveOrderInDatabase(Enum订单类型.坚山美国订单);
                }
                this.splashScreenManager.CloseWaitForm();
                MessageBox.Show("保存成功");

            }
            catch (Exception ex)
            {
                this.splashScreenManager.CloseWaitForm();
                MessageBox.Show(ex.Message);
            }
        }

        private void tileBarItem5_ItemClick(object sender, TileItemEventArgs e)
        {
            new Frm客户("52").ShowDialog();
            Frm客户.cUSTOMER_ID = 0;
            Frm客户.customer_name = "";
            Frm客户.customer_countid = 0;
            Frm客户.aDDRESS_ID = 0;
            this.查询客户();
        }
        private void comboBox门店_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.锁定地址();
        }

        private void 锁定地址()
        {
            switch (this.comboBox门店.Text.Trim())
            {
                case "上海坚山":
                    switch (this.comboBox邮寄地址.Text.Trim())
                    {
                        //默认邮寄到门店，布尔值为true
                        case "门店":
                            Frm客户.aDDRESS_ID = 7722;
                            this.expressToStore = true;
                            break;
                        //如果勾选邮寄客户地址，布尔值为false
                        case "客户地址":
                            Frm客户.aDDRESS_ID = this.trueAddressId;
                            this.expressToStore = false;
                            break;
                    }
                    break;
                default:
                    Frm客户.aDDRESS_ID = this.trueAddressId;
                    break;
            }

            /*
             * 当是受托加工的时候，从POST /outSourcing/getOutSourcingByShopCds取地址
             */
            //  邮寄地址
            if (this.expressToStore)
            {
                this.addressDTO = CRM客户Service.getOutSourcingByShopCd("KASHIYAMA_SH");
            }
            else
            {
                if(Frm客户.aDDRESS_ID!=0)
                this.addressDTO = CRM客户Service.getCustomerAddressById(Frm客户.aDDRESS_ID);
            }
            this.label地址.Text = addressDTO.toString();
            //String sql = "SELECT\n" +
            //            "	CONCAT( CONSIGNEE, '_', MOBILE, '_', ADDRESS_PROVINCE_CD, ADDRESS_CITY_CD, ADDRESS_DISTRICT, ADDRESS_DETAIL, ZIP_CODE ) AS ADDRESS \n" +
            //            "FROM\n" +
            //            "	a_customer_address_p \n" +
            //            "WHERE\n" +
            //            "	ADDRESS_ID = '" + Frm客户.aDDRESS_ID + "';";
            //DataRow dr = SQLmtm.GetDataRow(sql);
            //if (dr != null)
            //{
            //    this.label地址.Text = dr["ADDRESS"].ToString();
            //}
            //else
            //{
            //    this.label地址.Text = "";
            //}
        }

        private void comboBox邮寄地址_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.锁定地址();
        }

        private void 修改客户量体ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            new Frm新建客户量体(Frm客户.customer_countid,this.customerInformations).ShowDialog();
            this.查询客户量体(Frm客户.cUSTOMER_ID);
        }
    }
}
